﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using mmCore.Classes;
using mmCore.Interfaces;
using mmGoogleDataProvider;
using mmXmlDataProvider;

namespace mmUI.Managers
{
    public enum ProviderType
    {
        XmlFile,
        GoogleAccount,
        Unknown
    }

    public class MovieManager
    {
        private static readonly ObservableCollection<Movie> _mMovies = new ObservableCollection<Movie>();

        public static ObservableCollection<Movie> Movies
        {
            get { return _mMovies; }
        }

        private static string _mPath;

        public static event Action<List<Movie>> OnLoaded;
        public static event Action OnSaved;


        public static void LoadMovies(string path)
        {
            _mPath = path;

            IDataProvider provider = new XmlDataProvider();
            var movies = ((XmlDataProvider)provider).ReadMovies(path);

            if(Config.ProviderType == ProviderType.GoogleAccount)
            {
                provider = new GoogleDataProvider();
                var byteArray = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Config.GoogleLogin, Config.Password));
                var stream = new MemoryStream(byteArray); 
                var gmovies = provider.ReadMovies(stream);

                if (movies != null && gmovies != null && movies.Count > 0)
                {
                    foreach (var movie in movies.Where(movie => gmovies.Where(m => m.Id == movie.Id).Count() == 0))
                    {
                        gmovies.Add(movie);
                    }
                }
                movies = gmovies;
            }

            if (OnLoaded != null)
            {
                OnLoaded(movies);
            }
        }

        public static void AcceptLoadedMovies(List<Movie> movies)
        {
            _mMovies.Clear();
            foreach (var movie in movies)
            {
                _mMovies.Add(movie);
            }
        }

        public static void SaveMovies()
        {
            IDataProvider provider = new XmlDataProvider();
            ((XmlDataProvider)provider).SaveMovies(_mPath, _mMovies.ToList());

            if(Config.ProviderType == ProviderType.GoogleAccount)
            {
                provider = new GoogleDataProvider();
                var byteArray = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Config.GoogleLogin, Config.Password));
                var stream = new MemoryStream(byteArray); 
                provider.SaveMovies(stream, _mMovies.ToList());
            }
            if (OnSaved != null)
            {
                OnSaved();
            }
        }
    }
}
